package com.sandy.demo.auth

import groovy.transform.CompileStatic
import groovy.util.logging.Slf4j
import org.springframework.security.authentication.AuthenticationProvider
import org.springframework.security.core.Authentication
import org.springframework.security.core.AuthenticationException
import org.springframework.security.core.userdetails.UserDetails
import org.springframework.util.Assert

@Slf4j
@CompileStatic
class RestAuthenticationProvider implements AuthenticationProvider {

    TokenStorageService tokenStorageService = new MemoryTokenStorageService()

    Authentication authenticate(Authentication authentication) throws AuthenticationException {
        Assert.isInstanceOf(AccessToken, authentication, "Only AccessToken is supported")
        def token = authentication as AccessToken
        def authResult = new AccessToken(token.accessToken)

        if (token.accessToken) {
            log.debug "Trying to validate token ${token.accessToken}"
            def userDetails = tokenStorageService.loadUserByToken(token.accessToken)

            authResult = new AccessToken(userDetails, userDetails.authorities, token.accessToken)
            log.debug "Authentication result: ${authResult}"
        }

        return authResult
    }

    boolean supports(Class<?> authentication) {
        return AccessToken.isAssignableFrom(authentication)
    }
}
